package com.feng.cloud.common.configure;

import com.feng.cloud.common.configure.properties.GatewayTokenProperties;
import com.feng.cloud.common.constants.SystemConstant;
import com.feng.cloud.common.utils.WebUtils;
import com.google.common.net.HttpHeaders;
import feign.Request;
import feign.RequestInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Map;

/**
 * @ClassName OAuth2FeignConfigure
 * @Description TODO
 * @Author Better Feng
 * @Date 2020/1/8 16:09
 * @Version 1.0
 **/
@Configuration
@AllArgsConstructor
public class OAuth2FeignConfigure {

    private GatewayTokenProperties gatewayTokenProperties;

    @Bean
    public RequestInterceptor oauth2FeignRequestInterceptor() {
        return requestTemplate -> {
            // 请求头中添加 Gateway Token
            requestTemplate.header(gatewayTokenProperties.getName(), gatewayTokenProperties.getSecretKey());
            Request request = requestTemplate.request();
            Map<String, Collection<String>> headers = request.headers();
            Collection<String> headerList = headers.get(HttpHeaders.AUTHORIZATION);
            if (CollectionUtils.isEmpty(headerList)) {
                // 请求头中添加原请求头中的 Token
                String authorizationToken = WebUtils.getCurrentTokenValue();
                requestTemplate.header(HttpHeaders.AUTHORIZATION, SystemConstant.OAUTH2_TOKEN_TYPE + authorizationToken);
            }
        };
    }

}
